﻿// ===============================================================================
// SimpleRule.cs
// EOS Framework
// ===============================================================================
// Copyright (c) EOS Development Group. All rights reserved.
// ===============================================================================

namespace EOS.Framework.Rules
{
    using System;

    /// <summary>
    /// A simple type of domain object rule that uses a delegate for validation. 
    /// </summary>
    /// <returns>True if the rule has been followed, or false if it has been broken.</returns>
    /// <example>
    /// <code>
    /// this.Rules.Add(new SimpleRule("The customer name must be at least 5 letters long.", delegate { return this.Name &gt; 5; } ));
    /// </code>
    /// </example>
    public delegate bool SimpleRuleHandler(object value);

    /// <summary>
    /// A class to define a simple rule, using a delegate for validation.
    /// </summary>
    public class SimpleRule :  Rule
    {
        private SimpleRuleHandler ruleDelegate;

        /// <summary>
        /// Gets or sets the delegate used to validate this rule.
        /// </summary>
        protected virtual SimpleRuleHandler RuleDelegate
        {
            get { return ruleDelegate; }
            set { ruleDelegate = value; }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="SimpleRule"/> class.
        /// </summary>
        /// <param name="brokenDescription">A description message to show if the rule has been broken.</param>
        /// <param name="ruleDelegate">A delegate that takes no parameters and returns a boolean value, used to validate the rule.</param>        
        /// <exception cref="ArgumentNullException"><paramref name="brokenDescription"/> is
        /// null (Nothing in Visual Basic).</exception>
        /// <exception cref="ArgumentException"><paramref name="brokenDescription"/> is a string
        /// of length 0 or contains only blanks.</exception>
        public SimpleRule(string brokenDescription, SimpleRuleHandler ruleDelegate)
            : base(brokenDescription)
        {
            this.ruleDelegate = ruleDelegate;
        }

        /// <summary>
        /// Validates that the rule has not been broken.
        /// </summary>
        /// <param name="domainObject">The domain object being validated.</param>
        /// <returns>True if the rule has not been broken, or false if it has.</returns>
        public override bool Validate(object value)
        {
            return RuleDelegate(value);
        }
    }
}
